package com.industrial.operation.utils;


import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

public class MapUtils {


    /**
     *根据经纬度获取省市区
     */
    public static String getAddressStr(String log, String lat){
        //lat 小  log  大
        String key = "503b50ff7c33d5635dbe1e1563e20a7f";
        String parameters="?key="+key;
        parameters+="&location="+log+","+lat;//经纬度坐标
        parameters+="&extensions=true";//返回结果控制，extensions 参数取值为 all 时会返回基本地址信息、附近 POI 内容、道路信息以及道路交叉口信息。
        parameters+="&radius=1";//搜索半径，radius取值范围在0~3000，默认是1000。单位：米
        parameters+="&batch=false";
        parameters+="&roadlevel=0";

        String urlString = "https://restapi.amap.com/v3/geocode/regeo"+parameters;
        StringBuilder res = new StringBuilder();
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res.append(line).append("\n");
            }
            in.close();
            //解析结果
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(res.toString());
            System.out.println("jsonObject = " + jsonObject);
            JSONObject jsonObject1 = jsonObject.getJSONObject("regeocode");
            res = new StringBuilder(jsonObject1.getString("formatted_address"));
            JSONObject jsonObject2 = jsonObject1.getJSONObject("addressComponent");
            StringBuilder privince= new StringBuilder(jsonObject2.getString("province"));
            System.out.println("privince:"+privince);
            StringBuilder city= new StringBuilder(jsonObject2.getString("city"));
            System.out.println("city:"+city);
            StringBuilder district= new StringBuilder(jsonObject2.getString("district"));
            System.out.println("district:"+district);


        } catch (Exception e) {
            System.out.println("获取地址信息异常");
            e.printStackTrace();
            return null;
        }
        System.out.println("通过API获取到具体位置:"+res);

        return res.toString();
    }



    /**
     *根据经纬度获取省市区
     */
    public static Map getAddress(String log, String lat){
        Map map=new HashMap();
        //lat 小  log  大
        String key = "503b50ff7c33d5635dbe1e1563e20a7f";
        String parameters="?key="+key;
        parameters+="&location="+log+","+lat;//经纬度坐标
        parameters+="&extensions=true";//返回结果控制，extensions 参数取值为 all 时会返回基本地址信息、附近 POI 内容、道路信息以及道路交叉口信息。
        parameters+="&radius=1";//搜索半径，radius取值范围在0~3000，默认是1000。单位：米
        parameters+="&batch=false";
        parameters+="&roadlevel=0";

        String urlString = "https://restapi.amap.com/v3/geocode/regeo"+parameters;
        StringBuilder res = new StringBuilder();
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res.append(line).append("\n");
            }
            in.close();
            //解析结果
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(res.toString());
            System.out.println("jsonObject = " + jsonObject);
            JSONObject jsonObject1 = jsonObject.getJSONObject("regeocode");
            res = new StringBuilder(jsonObject1.getString("formatted_address"));

            System.out.println("通过API获取到具体位置:"+res);
            JSONObject jsonObject2 = jsonObject1.getJSONObject("addressComponent");
            StringBuilder privince= new StringBuilder(jsonObject2.getString("province"));
            System.out.println("privince:"+privince);
            StringBuilder city= new StringBuilder(jsonObject2.getString("city"));
            System.out.println("city:"+city);
            StringBuilder district= new StringBuilder(jsonObject2.getString("district"));
            System.out.println("district:"+district);
            map.put("privince",privince.toString());
            map.put("city",city.toString());
            map.put("district",district.toString());
            map.put("address",res.toString());
        } catch (Exception e) {
            System.out.println("获取地址信息异常");
            e.printStackTrace();
            return null;
        }


        return map;
    }

   /* public static void main(String[] args) {
        getLonAndLat("山东省济南市天桥区虎泉信息科技中心");
    }*/
   public static Map getLonAndLat(String addr) throws IOException {
       String lng = null;//经度
       String lat = null;//纬度
       String address = null;
       Map<String, String> map = new HashMap<String, String>();
       try {
           address = java.net.URLEncoder.encode(addr, "UTF-8");
       }catch (UnsupportedEncodingException e1) {
           e1.printStackTrace();
       }
       String key = "f247cdb592eb43ebac6ccd27f796e2d2";
       String url = String.format("http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s", address, key);
       URL myURL = null;
       URLConnection httpsConn = null;
       try {
           myURL = new URL(url);
       } catch (MalformedURLException e) {
           e.printStackTrace();
       }
       InputStreamReader insr = null;
       BufferedReader br = null;
       try {
           httpsConn = (URLConnection) myURL.openConnection();// 不使用代理
           if (httpsConn != null) {
               insr = new InputStreamReader( httpsConn.getInputStream(), "UTF-8");
               br = new BufferedReader(insr);
               String data = null;
               int count = 1;
               while((data= br.readLine())!=null){
                   if(count==5){
                       lng = (String)data.subSequence(data.indexOf(":")+1, data.indexOf(","));//经度
                       count++;
                   }else if(count==6){
                       lat = data.substring(data.indexOf(":")+1);//纬度
                       count++;
                   }else{
                       count++;
                   }
               }
           }
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           if(insr!=null){
               insr.close();
           }
           if(br!=null){
               br.close();
           }
       }
       if (lng != null && lat!=null) {
           map.put("lng", lng);
           map.put("lat", lat);
       }
       System.out.println(map);
       return map;
   }


   /* public static Map getLonAndLat(String address) {
        String key = "503b50ff7c33d5635dbe1e1563e20a7f";
        // 返回输入地址address的经纬度信息, 格式是 经度,纬度
        String queryUrl = "http://restapi.amap.com/v3/geocode/geo?key=" + key + "&address=" + address;
        // 高德接口返回的是JSON格式的字符串
        String queryResult = getResponse(queryUrl);
        Map<String, String> map = new HashMap<String, String>();
        JSONObject obj = JSONObject.parseObject(queryResult);
        if (obj.get("status").toString().equals("1")) {
            JSONObject jobJSON = JSONObject.parseObject(obj.get("geocodes").toString().substring(1, obj.get("geocodes").toString().length() - 1));
            String location = jobJSON.get("location").toString();
            System.out.println("经纬度：" + location);
            String[] lonAndLat = location.split(",");
            if (lonAndLat != null && lonAndLat.length == 2) {
                map.put("lng", lonAndLat[0]);
                map.put("lat", lonAndLat[1]);
            }
            System.out.println(map);
            return map;
        } else {
            throw new RuntimeException("地址转换经纬度失败，错误码：" + obj.get("infocode"));
        }
    }*/

    private static String getResponse(String serverUrl) {
        // 用JAVA发起http请求，并返回json格式的结果
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(serverUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    public static void main(String[] args) throws IOException {
        Map map=    getLonAndLat("山东省青岛市即墨区汽车产业新城康泉一路11号");
        System.out.println("1111");
    }
}
